let title = ''
let content = ''
let loadding = 'lodding'
const db = wx.cloud.database()
const p_db = db.collection('publish')
let datas
let cloudPathList = []
const app = getApp()

Page({
 
  data: {
    yes:'yes',

    time: '',
 
    imgPreview: '',
 
    imgList: [],
 
    temFile: '',

    previewimg:'cloud://cloud1-7gp73os4feb4632b.636c-cloud1-7gp73os4feb4632b-1315259068/icon/添加.png'
  },

  onShow(){

},

  /** 上传按钮点击监听 */
  async uploadFileTap(res) {
    // 上传类型
    const type = res.currentTarget.dataset.type
    let filePathObj = null
    let filePathList = []

    if (type == 'file') {
      filePathObj = await this.chooseMessageFile(1, 'file')
      if (!filePathObj) return
      filePathList.push(filePathObj.tempFiles[0].path)
    } else if (type == 'img') {
      filePathObj = await this.chooseImg(2)
      if (!filePathObj) return
      filePathList = filePathObj.tempFilePaths
    } else {
      return
    }

    console.log("选择文件信息 ====>", filePathObj)
    for (let i = 0; i < filePathList.length; i++) {
      const cloudPathObj = await this.upLoadFile(filePathList[i], 'file')
      if (!cloudPathObj) {
        continue
      }
      console.log(filePathList[i], "文件上传成功=====>", cloudPathObj)
      cloudPathList.push(cloudPathObj.fileID)
    }

    console.log("最终返回云文件ID列表 =====>", cloudPathList)
    this.setData({
        previewimg:cloudPathList
      })

  },

  /**
   * 从聊天记录选择文件
   * @param {number} count 可选择数量（1-100）
   * @param {string} type 可选择文件类型 all:全部类型 video: 仅视频 image: 仅图片 file: 除了视频、图片外的文件类型
   */
  chooseMessageFile(count, type) {
    return new Promise((resolve, reject) => {
      wx.chooseMessageFile({
        count: count,
        type: type,
        success(res) {
          resolve(res)
        },
        fail(err) {
          console.log("选择文件错误 =====>", err)
          resolve(false)
        }
      })
    })
  },

  /** 选择图片封装函数
   * @param count 照片数量
   * @param sizeType 照片的质量, 默认 ['original', 'compressed']
   * @param sourceType 照片来源, 默认 ['album', 'camera']
   */
  chooseImg(count, sizeType, sourceType) {
    if (!count) count = 1
    if (!sizeType) sizeType = ['original', 'compressed']
    if (!sourceType) sourceType = ['album', 'camera']
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        count: count,
        sizeType: sizeType,
        sourceType: sourceType,
        success(res) {
          resolve(res)
        },
        fail(err) {
          resolve(false)
          console.error("===== 选取照片失败 =====", err)
        }
      })
    })
  },

  /** 
   * 上传文件封装函数, 文件名随机性处理，由17位随机字符+13位时间戳组成
   * @param {string} filePath 要上传图片的临时路径
   * @param {string} cloudPathPrefix 云数据库存储文件路径前缀
   */
  upLoadFile(filePath, cloudPathPrefix) {
    // 取随机名
    let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let randomStr = '';
    for (let i = 17; i > 0; --i) {
      randomStr += str[Math.floor(Math.random() * str.length)];
    }
    randomStr += new Date().getTime()

    return new Promise((resolve, reject) => {
      let suffix = /\.\w+$/.exec(filePath)[0] //正则表达式返回文件的扩展名
      let cloudPath = cloudPathPrefix + '/' + randomStr + suffix
      wx.cloud.uploadFile({
        cloudPath: cloudPath,
        filePath: filePath,
        success(res) {
          resolve(res)
          wx.showToast({
            title: '上传成功',
            icon:"success"
          })
        },
        fail(err) {
          resolve(false)
          console.error("===== 上传文件失败 =====", err)
        },
      })
    })
  },

  onLoad: function(options) {
    p_db
    .get()
    .then(res=>{
      this.setData({
        yes:res.data[0].yes
      })
    })
      console.log(app.globalData.userInfo)
  },
 
  title_input(e) {
 
    title = e.detail.value
 
    console.log(title)
    this.setData({
        inputValue: title
    })
  },
 
  content_input(e) {
    content = e.detail.value
 
    console.log(content)
    this.setData({
        inputValue: content
    })
  },
 
  chooseImage() {
 
    wx.chooseImage({
 
      count: 9,
 
      sizeType: ['compressed', 'original'],
 
      sourceType: ['album', 'camera'],
 
      success: res => {
 
        // this.uploadImg(res.tempFilePaths[0])
 
 
 
        this.setData({
 
          imgList: this.data.imgList.concat(res.tempFilePaths),
 
          temFile: res.tempFilePaths
 
        })
 
      },
 
      fail(err) {
 
        console.log("选择失败", err)
 
      }
 
    })
 
    // 将图片上传至云存储空间
 
  },
 
  uploadImg(temFile) {
 
    for (let i = 0; i < this.data.imgList.length; i++) {
 
      let m = Math.random() * 100
 
      wx.cloud.uploadFile({
 
        cloudPath: ('imgList/帖子/' + m + '.png'), // 指定要上传的文件的小程序临时文件路径
 
        filePath: this.data.temFile[i],
 
        success: res => { // 成功回调
 
          console.log('上传成功', res)
 
        },
 
        fail(err) {
 
          console.log("失败", err)
 
        }
 
      })
 
    }
 
  },
 
preview(e) { //预览图片
 
    let img = e.currentTarget.dataset.src;
 
    let imgList = this.data.imgList;
 
    imgList.push(img);
 
    wx.previewImage({
 
      current: img, // 当前显示图片的http链接
 
      urls: imgList // 需要预览的图片http链接列表
 
    })
 
  },
 
  delImg(e) { //删除图片
 
    let that = this;
 
    console.log('点击删除图片===>', e);
 
    let index = e.currentTarget.dataset.index;
 
    let imgList = that.data.imgList;
 
    wx.showModal({
 
      title: '提示',
 
      content: '删除该图片？',
 
      confirmColor: 'red',
 
      success(res) {
 
        if (res.confirm) {
 
          console.log('用户点击确定')
 
          imgList.splice(index, 1);
 
          that.setData({
 
            imgList
 
          })
 
        } else if (res.cancel) {
 
          console.log('用户点击取消')
 
        }
 
      }
 
    })
 
  },
 
  // 删除选中的图片
 
  deleteImg: function () {
 
    const {
 
      imgPreview
 
    } = this.data
 
    this.setData({
 
      imgPreview: ''
 
    })
 
  },
 
  fabu() {
 
    this.uploadImg(this.data.temFile)
 
    var date = new Date();
 
    var Y = date.getFullYear();
 
    var M = date.getMonth() + 1;
 
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
 
    var H = date.getHours()
 
    var min = date.getMinutes()
 
    this.setData({ 
      time: M + "-" + D + " " + H + ":" + min
    })
 
 
 
    console.log("标题：", title)
 
    console.log("内容", content)
 
    if (title && content) {
 
      console.log("可以发布")
 
      let account = wx.getStorageSync('account')
 
      let myname = app.globalData.userInfo.nickName

      let avatar = app.globalData.userInfo.avatarUrl
 
      wx.cloud.database().collection('articlelist')
 
        .add({
 
          data: {
 
            title: title,
 
            content: content,

            status: 0,
  
            comments: [],

            collector: [],
 
            name: myname,
 
            time: this.data.time,

            avatar:avatar, 

            coverimages: cloudPathList[0],

            createTime:db.serverDate()
          },
 
        }).then(res => {
 
          console.log("提交成功")
 
          wx.showToast({
 
            icon: 'success',
 
            title: '发布成功',
 
          }),
          setTimeout(
            function(){
                wx.switchTab({
                    url:'../social/social'
                  })
            },2000)
        }).catch(res => {
 
          console.log("提交失败")
 
        })

 
 
    } else {
 
      wx.showToast({
 
        icon: 'error',
 
        title: '标题或者内容为空',
 
      })
 
    }
 
  },
  onPullDownRefresh: function () {       // 下拉刷新
    var page = getCurrentPages().pop();  // 得到这个页面对象
    page.onLoad();                       // 调用页面的onLoad()方法进行刷新页面
    wx.stopPullDownRefresh()             // 刷新成功后停止下拉刷新
 },
})

